package com.arp;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.arp.dao.Tables;


public class MiniProjectActivity extends Activity implements OnClickListener, OnItemClickListener{
    
	private EditText new_text;
	private Cursor cursor;
	private SimpleCursorAdapter cursorAdapter;
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ListView listContent = (ListView)findViewById(R.id.listView1);
        new_text = (EditText)findViewById(R.id.text_new);
        
        
        Button new_btn = (Button)findViewById(R.id.button_new);
        new_btn.setOnClickListener(this);
        
        
        ((ListView)findViewById(R.id.listView1)).setOnItemClickListener(new MyListListener());
        listContent.setFocusable(true);
        listContent.setFocusableInTouchMode(true);
        listContent.setOnCreateContextMenuListener(this);   
        
        //listContent.setClickable(true);
        listContent.setOnItemClickListener(this);
        
        
//        
//        listContent.setOnItemSelectedListener(new OnItemSelectedListener(){
//        	@Override
//        	public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
//        		Log.i("DEBUG", "ID=" + id);
//        		Toast.makeText(getApplicationContext(), "ID = " + id, Toast.LENGTH_LONG); 	
//        	}
//        	
//        	public void onNothingSelected(AdapterView<?> parent){
//        		
//        	}
//        }
//        );
        
        Intent i = getIntent();
        if (i.getData()==null)
        	i.setData(Tables.ShopList.CONTENT_URI);
        
        String[] PROJECTION = new String[] {
        	Tables.ShopList._ID,
        	Tables.ShopList._NAME
    	};
        
        
        cursor = null;
        try {
            cursor = this.getContentResolver().query(i.getData(), PROJECTION, null, null, null);
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        startManagingCursor(cursor);
        
        String[] dataColumns = new String[]{Tables.ShopList._NAME};
        int[] viewIDs = new int[]{ /*R.id.item_id,*/  R.id.name};
        
        cursorAdapter
        = new SimpleCursorAdapter(
                  this,                             // The Context for the ListView
                  R.layout.shoplist_item2,          // Points to the XML for a list item
                  cursor,                           // The cursor to get items from
                  dataColumns,
                  viewIDs
          );
        
                
        listContent.setAdapter(cursorAdapter);
        
        
    }
    
    @Override
    public void onClick(View source){
    	String text = "" + new_text.getText();
		if (text.length()>0){
			ContentValues values = new ContentValues();
			values.put(Tables.ShopList._NAME, text);
			
			getContentResolver().insert(Tables.ShopList.CONTENT_URI, values);
			new_text.setText("");
			cursor.requery();
		}
    }
    
    
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {

        // The data from the menu item.
        AdapterView.AdapterContextMenuInfo info;

        // Tries to get the position of the item in the ListView that was long-pressed.
        try {
            // Casts the incoming data object into the type for AdapterView objects.
            info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            // If the menu object can't be cast, logs an error.
            Log.e("Fejl40", "bad menuInfo", e);
            return;
        }

        /*
         * Gets the data associated with the item at the selected position. getItem() returns
         * whatever the backing adapter of the ListView has associated with the item. In NotesList,
         * the adapter associated all of the data for a note with its list item. As a result,
         * getItem() returns that data as a Cursor.
         */
        Cursor cursor = (Cursor) cursorAdapter.getItem(info.position);

        // If the cursor is empty, then for some reason the adapter can't get the data from the
        // provider, so returns null to the caller.
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }

        // Inflate menu from XML resource
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.shoplist_menu, menu);

        // Sets the menu header to be the title of the selected note.
        menu.setHeaderTitle(cursor.getString(cursor.getColumnIndex(Tables.ShopList._NAME)));

        // Append to the
        // menu items for any other activities that can do stuff with it
        // as well.  This does a query on the system for any activities that
        // implement the ALTERNATIVE_ACTION for our data, adding a menu item
        // for each one that is found.
//        Intent intent = new Intent(null, Uri.withAppendedPath(getIntent().getData(), 
//                                        Integer.toString((int) info.id) ));
//        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
//        menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
//                new ComponentName(this, NotesList.class), null, intent, 0, null);
    }

    /**
     * This method is called when the user selects an item from the context menu
     * (see onCreateContextMenu()). The only menu items that are actually handled are DELETE and
     * COPY. Anything else is an alternative option, for which default handling should be done.
     *
     * @param item The selected menu item
     * @return True if the menu item was DELETE, and no default processing is need, otherwise false,
     * which triggers the default handling of the item.
     * @throws ClassCastException
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // The data from the menu item.
        AdapterView.AdapterContextMenuInfo info;

        /*
         * Gets the extra info from the menu item. When an note in the Notes list is long-pressed, a
         * context menu appears. The menu items for the menu automatically get the data
         * associated with the note that was long-pressed. The data comes from the provider that
         * backs the list.
         *
         * The note's data is passed to the context menu creation routine in a ContextMenuInfo
         * object.
         *
         * When one of the context menu items is clicked, the same data is passed, along with the
         * note ID, to onContextItemSelected() via the item parameter.
         */
        try {
            // Casts the data object in the item into the type for AdapterView objects.
            info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {

            // If the object can't be cast, logs an error
            Log.e("Fejl40", "bad menuInfo", e);

            // Triggers default processing of the menu item.
            return false;
        }
        // Appends the selected note's ID to the URI sent with the incoming Intent.
        Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), info.id);

        /*
         * Gets the menu item's ID and compares it to known actions.
         */
        switch (item.getItemId()) {
        case R.id.button_delete :
            
        	this.getContentResolver().delete(Tables.ShopList.CONTENT_URI, "_id=?", new String[]{"" + info.id});
        	cursor.requery();
            
            return true;

                default:
            return super.onContextItemSelected(item);
        }
    }
    
    
    
    
    
    public class MyListListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Log.i("List", "ID=" + id);
			Toast.makeText(getApplicationContext(), "ID = " + id, Toast.LENGTH_LONG);
			
		}
    	
    }
    
    
//    @Override
//    protected void onListItemClick(ListView l, View v, int position, long id) {
//    	Log.i("DEBUG", "ID=" + id);
//    	Toast.makeText(getApplicationContext(), "ID = " + id, Toast.LENGTH_LONG);
//    	//super.onListItemClick(l, v, position, id);
//        //Intent i = new Intent(this, NoteEdit.class);
//        //i.putExtra(NotesDbAdapter.KEY_ROWID, id);
//        //startActivityForResult(i, ACTIVITY_EDIT);
//    }
    
    public class MyListAdapter extends SimpleCursorAdapter{

    	
    	
		public MyListAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
			// TODO Auto-generated constructor stub
		}

    }
    
    public class VB implements SimpleCursorAdapter.ViewBinder{
    	private AdapterView<?> parent;
    	private List<OnItemClickListener> events = new ArrayList<OnItemClickListener>();
    	
    	private void fireClickEvent(){
    		
    		parent.performClick();
    	}
    	
    	public VB(AdapterView<?> parent){
    		this.parent = parent;
    	}
    	
		@Override
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
			if (!(view instanceof Button) ){
				((TextView)view).setText(cursor.getString(columnIndex));	
				view.setOnClickListener(new MyClickListener(cursor.getPosition(), cursor.getInt(cursor.getColumnIndex(Tables.ShopList._ID)))); 
				
				view.setClickable(true);
				view.setFocusable(true);
				view.setFocusableInTouchMode(true);
				view.setBackgroundResource(android.R.drawable.menuitem_background);
				
				((TextView) view).setPadding(10, 0, 0, 0);
				
				view.requestLayout();
				return true;
			} else {
				view.setClickable(true);
				view.setFocusable(true);
				view.setFocusableInTouchMode(true);
				view.setOnClickListener(new MyButtonClickListener(getApplicationContext(), cursor.getPosition(), cursor.getInt(cursor.getColumnIndex(Tables.ShopList._ID))));
				//view.setBackgroundResource(android.R.drawable.menuitem_background);
				return false;
			}
		}
		
		public class MyClickListener implements OnClickListener{
			
			private int position;
			private int _id;
			
			public MyClickListener(int position, int _id){
				this.position = position;
				this._id = _id;
			}
			
			@Override
			public void onClick(View v) {
				Log.i("onClick",  "RowId=" + _id + "(pos=" + position + ")");
				fireClickEvent();
				//ViewParent vp = v.getParent();
				//((Button)((View) vp).findViewById(R.id.shoplist_item_button_slet)).setBackgroundResource(android.R.drawable.menuitem_background);
				//v.setBackgroundColor(Color.RED);
				//v.forceLayout();
			}
		}
		
		
		public class MyButtonClickListener implements OnClickListener{
			
			private int position;
			private int _id;
			private Context context;
			
			public MyButtonClickListener(Context context, int position, int _id){
				this.position = position;
				this._id = _id;
			}
			
			@Override
			public void onClick(View v) {
				Log.i("onClickButton",  "button RowId=" + _id + "(pos=" + position + ")");
				Toast.makeText(context, "Delete " + _id, Toast.LENGTH_SHORT);
			}
		}
    	
    }

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		//TODO new Activity with ID		
		
	}
    
}